<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace app\common\logic;

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;

/**
 * Class OssLogic
 * 对象存储逻辑类
 */
class OssLogic
{
    static private $initConfigFlag = false;
    static private $accessKeyId = '';
    static private $accessKeySecret = '';
    static private $securityToken = '';
    static private $endpoint = '';
    static private $bucket = '';
    static private $instance = null;

    /** @var \OSS\OssClient */
    static private $ossClient = null;
    static private $errorMsg = '';


    static private $waterPos = [
        1 => 'nw',     //标识左上角水印
        2 => 'north',  //标识上居中水印
        3 => 'ne',     //标识右上角水印
        4 => 'west',   //标识左居中水印
        5 => 'center', //标识居中水印
        6 => 'east',   //标识右居中水印
        7 => 'sw',     //标识左下角水印
        8 => 'south',  //标识下居中水印
        9 => 'se',     //标识右下角水印
    ];

    public static $prefix = '@oss@';

    public function __construct()
    {
        self::initConfig();
    }

    /**
     * User:Simony
     * Function: 单例
     * @return OssLogic|null
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * User:Simony
     * Function: 获取错误信息，一旦其他接口返回false时，可调用此接口查看具体错误信息
     * @return string
     */
    public function getError()
    {
        return self::$errorMsg;
    }

    /**
     * User:Simony
     * Function: 初始化配置
     */
    static private function initConfig()
    {
        if (self::$initConfigFlag) return;

        $ossConfig = sysConfig('oss');
        self::$accessKeyId = $ossConfig['accessKeyId'] ?? '';
        self::$accessKeySecret = $ossConfig['accessKeySecret'] ?? '';
        self::$endpoint = $ossConfig['endpoint'] ?? '';
        self::$bucket = $ossConfig['bucket'] ?? '';
        self::$securityToken = $ossConfig['securityToken'] ?? '';
        self::$initConfigFlag = true;
    }

    /**
     * User:Simony
     * Function:
     * @return null|OssClient
     */
    static private function getOssClient()
    {
        if (!self::$ossClient) {
            self::initConfig();
            try {
                if (empty(self::$securityToken)) {
                    self::$ossClient = new OssClient(self::$accessKeyId, self::$accessKeySecret, self::$endpoint, false);
                } else {
                    self::$ossClient = new OssClient(self::$accessKeyId, self::$accessKeySecret, self::$endpoint, false, self::$securityToken);
                }

            } catch (OssException $e) {
                self::$errorMsg = "创建oss对象失败，" . $e->getMessage();
                return null;
            }
        }
        return self::$ossClient;
    }

    /**
     * User:Simony
     * Function: 获取路径
     * @return string
     */
    public function getSiteUrl()
    {
        return "https://" . self::$bucket . "." . self::$endpoint;
    }

    /**
     * User:Simony
     * Function: 上传文件
     * @param $filePath
     * @param null $object
     * @return bool|string
     */
    public function uploadFile($filePath, $object = null)
    {
        $ossClient = self::getOssClient();

        if (!$ossClient) return false;

        if (is_null($object)) $object = str_replace('\\','/',$filePath);

        try {
            $ossClient->uploadFile(self::$bucket, $object, $filePath);
        } catch (OssException $e) {
            self::$errorMsg = "oss上传文件失败，" . $e->getMessage();
            return false;
        }
        return $this->getSiteUrl() . '/' . $object;
    }

    /**
     * User:Simony
     * Function: 链接加上文本水印参数（文字水印(方针黑体，黑色)）
     * @param $url
     * @param $text
     * @param $size
     * @param $color
     * @param $transparency
     * @param $posSel
     * @return string
     */
    private function withTextWaterUrl($url, $text, $size, $color, $transparency, $posSel)
    {
        $color = $color ?: '#000000';
        if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) $color = '#000000';
        $color = ltrim($color, '#');
        $text_encode = urlsafe_b64encode($text);
        $url .= ",image/watermark,text_{$text_encode},type_ZmFuZ3poZW5naGVpdGk,color_{$color},size_{$size},t_{$transparency},g_" . self::$waterPos[$posSel];
        return $url;
    }

    /**
     * User:Simony
     * Function: 链接加上图片水印参数
     * @param $url
     * @param $image
     * @param $transparency
     * @param $posSel
     * @return string
     */
    private function withImageWaterUrl($url, $image, $transparency, $posSel)
    {
        $image = ltrim(parse_url($image, PHP_URL_PATH), '/');
        $image_encode = urlsafe_b64encode($image);
        $url .= ",image/watermark,image_{$image_encode},t_{$transparency},g_" . self::$waterPos[$posSel];
        return $url;
    }

    /**
     * User:Simony
     * Function: 是否是oss的链接
     * @param $url
     * @return bool
     */
    public function isOssUrl($url)
    {
        if ($url && strpos($url, 'http') === 0 && strpos($url, 'aliyuncs.com')) return true;
        return false;
    }

    /**
     * User:Simony
     * Function: 删除文件
     * @param $object
     * @return bool
     */
    public function deleteFile($object)
    {
        $object = ltrim($object, '/');

        $ossClient = self::getOssClient();
        if (!$ossClient) return false;
        try {
            $result = $ossClient->deleteObject(self::$bucket, $object);
            return $result === false ? false : true;
        } catch (OssException $e) {
            self::$errorMsg = "oss删除文件失败，" . $e->getMessage();
            return false;
        }
    }


    public function signUrl($file_path)
    {
        $ossClient = self::getOssClient();
        try {
            $signedUrl = $ossClient->signUrl(self::$bucket, $file_path, "3600");
        } catch (OssException  $e) {
            print_r($e->getMessage());
            die;
        }
        echo strval($signedUrl) . "\n";
        die;
    }
}